import axios from "axios";
import {Toast} from "vant"; // 引入Vant组件库的提示组件
import router from "../router";
import {setLocal} from "utils/help.js";

axios.defaults.baseURL = import.meta.env.MODE == 'development' ? '//localhost:28019/api/v1' : '//localhost:28019/api/v1'
    axios.defaults.withCredentials = true
    axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest'
    axios.defaults.headers['token'] = localStorage.getItem('token') || ''
    axios.defaults.headers.post['Content-Type'] = 'application/json'

axios.interceptors.response.use(res => {
    // 若响应头内部data不为object，则视为服务器异常，这里直接使用Promise.reject抛出异常
    if (typeof res.data !== 'object') {
        Toast.fail('服务器异常')
        return Promise.reject(res)
    }
    if (res.data.resultCode != 200){
        if (res.data.message) Toast.fail(res.data.message)
        if (res.data.resultCode == 416){
            router.push({path: '/login'})
        }
        if (res.data.data && window.location.hash == '#/login') {
            setLocal('token', res.data.data)
            axios.defaults.headers['token'] = res.data.data
        }
        return Promise.reject(res.data)
    }
    return res.data
    }
)

export default axios
